from model import Process as ModelProcess
from model import Project as ModelProject
import datetime
from model import Mysql
import utils.jsonData as JsonData
from entity.Prosumer import PRODUCER, CONSUMER
from utils.prosumer_task import *
from service import logService


def start_local_process(_json):
    project_id = _json["project"]
    process_id = _json["process"]
    if (ModelProject.Project.update({
        ModelProject.Project.id: project_id,
        ModelProject.Project.status: True,
        ModelProject.Project.update_time: datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }).where(
        ModelProject.Project.id == project_id).execute() and
            ModelProcess.Process.update({
                ModelProcess.Process.project_id: int(project_id)
            }).where(
                ModelProcess.Process.id == process_id).execute()):
        process = ModelProcess.Process.get(ModelProcess.Process.id == process_id)
        project = ModelProject.Project.get(ModelProject.Project.id == project_id)
        _dict = dict()
        _dict["id"] = process.id
        _dict["ip"] = process.ip
        _dict["port"] = process.port
        _dict["project"] = project
        log_id = logService.create_log(process_id, process.ip, process.port, project_id, project.name)
        if log_id:
            CONSUMER.push(str(_dict["ip"]), "11002", "已经为本次运行记录至数据库", "")
        else:
            CONSUMER.push(str(_dict["ip"]), "11002", "创建历史记录失败", "")
        _dict["log_id"] = log_id
        PRODUCER.push(str(_dict["ip"]), start_local_process_task, _dict)
        return JsonData.JsonData().success_data(msg="已添加一个运行任务！")
    Mysql.db.rollback()
    return JsonData.JsonData().error(code="1008", msg="更新项目状态失败，请重试！")